package org.millioncall.yueyoga.admin.service.advancedsearch;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.common.GlobalConstants;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;

/**
 * 基于Aviator表达式的结果集处理器
 * 
 * @author zangjinyu
 * @since 1.0.0
 * @version 1.0.0
 * 
 */
public class AviatorResultHandler<T> implements ResultHandler {
	private final List<T> list;
	private AviatorExpression aviator;
	private Map<String, Object> params;
	private int limit = Integer.MAX_VALUE;
	private int count = 0;

	static {
		AviatorEvaluator.addFunction(new DateTimeUtilFunction());// 注入日期时间函数
	}

	public AviatorResultHandler(AviatorExpression aviator,
			Map<String, Object> params, int limit) {
		this.aviator = aviator;
		this.params = params;
		list = new ArrayList<T>();
		this.limit = limit;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handleResult(ResultContext context) {
		if (count < limit) {
			T result = (T) context.getResultObject();
			String modelKey = (String) params
					.get(GlobalConstants.RESULT_ROW_MODEL_KEY);
			params.put(modelKey, result);
			Expression compiledExp = AviatorEvaluator.compile(
					aviator.getExpression(), true);
			Boolean b = (Boolean) compiledExp.execute(params);
			if (b.booleanValue()) {
				list.add(result);
				count++;
			}
		}
	}

	public List<T> getResultList() {
		return list;
	}
}
